<template>
  <div class="user-log-view">
    <div class="container">
      <div class="top-bar">
        <h1>用户日志信息</h1>
        <button class="btn btn-primary stats-btn" @click="goStats">统计报表</button>
      </div>
      <div class="logs-section">
        <button class="tool-list-btn" @click="goHome">工具列表</button>
        <div class="query-row">
          <form class="query-form wide-form" @submit.prevent="onQuery">
            <input v-model="query.tool_name" placeholder="工具名称" class="query-input" />
            <input v-model="query.name" placeholder="用户姓名" class="query-input" />
            <input v-model="query.start" type="date" class="query-input" />
            <input v-model="query.end" type="date" class="query-input" />
            <button type="submit" class="btn btn-primary btn-wide">查询</button>
            <button @click.prevent="showAdd = true" class="btn btn-primary add-btn">新增</button>
          </form>
        </div>
        <div v-if="showAdd" class="modal">
          <div class="modal-content">
            <h3>新增日志</h3>
            <input v-model="newLog.name" placeholder="用户姓名" />
            <select v-model="newLog.tool_id">
              <option value="">请选择工具</option>
              <option v-for="tool in tools" :key="tool.uuid" :value="tool.uuid">{{ tool.name }}</option>
            </select>
            <input v-model="newLog.start_time" type="datetime-local" placeholder="开始使用时间" />
            <input v-model="newLog.ip" placeholder="IP" />
            <input v-model="newLog.computer_name" placeholder="电脑名" />
            <input v-model="newLog.use_time" placeholder="使用时间" />
            <button @click="handleAdd" class="btn btn-primary">提交</button>
            <button @click="showAdd = false" class="btn">取消</button>
          </div>
        </div>
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="error" class="error">{{ error }}</div>
        <div v-else-if="logs.length === 0" class="empty">暂无日志数据</div>
        <div v-else class="logs-table">
          <table>
            <thead>
              <tr>
                <th>编号</th>
                <th>使用人姓名</th>
                <th>工具名称</th>
                <th>开始使用时间</th>
                <th>IP</th>
                <th>电脑名</th>
                <th>使用时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(log, idx) in logs" :key="log.no">
                <td>{{ (page - 1) * pageSize + idx + 1 }}</td>
                <td v-if="log.editing"><input v-model="log.editCache.name" /></td>
                <td v-else>{{ log.name }}</td>
                <td v-if="log.editing">
                  <select v-model="log.editCache.tool_id">
                    <option value="">请选择工具</option>
                    <option v-for="tool in tools" :key="tool.uuid" :value="tool.uuid">{{ tool.name }}</option>
                  </select>
                </td>
                <td v-else>{{ log.tool_name }}</td>
                <td v-if="log.editing"><input v-model="log.editCache.start_time" type="datetime-local" /></td>
                <td v-else>{{ formatDateTime(log.start_time) }}</td>
                <td v-if="log.editing"><input v-model="log.editCache.ip" /></td>
                <td v-else>{{ log.ip }}</td>
                <td v-if="log.editing"><input v-model="log.editCache.computer_name" /></td>
                <td v-else>{{ log.computer_name }}</td>
                <td v-if="log.editing"><input v-model="log.editCache.use_time" /></td>
                <td v-else>{{ log.use_time }}</td>
                <td>
                  <button v-if="!log.editing" @click="startEdit(log)" class="btn btn-small btn-secondary">编辑</button>
                  <button v-if="log.editing" @click="saveEdit(log)" class="btn btn-small btn-primary">保存</button>
                  <button v-if="log.editing" @click="cancelEdit(log)" class="btn btn-small">取消</button>
                  <button @click="handleDelete(log.no)" class="btn btn-small btn-danger">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="pagination">
            <button :disabled="page === 1" @click="onPageChange(page - 1)">上一页</button>
            <span>第 {{ page }} 页 / 共 {{ Math.ceil(total / pageSize) || 1 }} 页</span>
            <button :disabled="page >= Math.ceil(total / pageSize)" @click="onPageChange(page + 1)">下一页</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const query = ref({
  tool_name: '',
  name: '',
  start: '',
  end: ''
})

interface UserLog {
  no: number
  name: string
  start_time: string
  ip: string
  computer_name: string
  use_time: string
  tool_id: string
  tool_name: string
  editing?: boolean
  editCache?: any
}

const logs = ref<UserLog[]>([])
const loading = ref(false)
const error = ref('')
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const showAdd = ref(false)
const newLog = ref({
  name: '',
  tool_id: '',
  start_time: '',
  ip: '',
  computer_name: '',
  use_time: ''
})

const tools = ref<{ uuid: string, name: string }[]>([])
async function loadTools() {
  const res = await fetch('http://localhost:3000/api/tools')
  const data = await res.json()
  if (data.success && data.data) tools.value = data.data
}

function formatDateTime(val: string) {
  if (!val) return '';
  const date = new Date(val);
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const min = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${min}:${s}`;
}

const loadLogs = async () => {
  loading.value = true
  error.value = ''
  try {
    const params = new URLSearchParams()
    if (query.value.tool_name) params.append('tool_name', query.value.tool_name)
    if (query.value.name) params.append('name', query.value.name)
    if (query.value.start) params.append('start', query.value.start)
    if (query.value.end) params.append('end', query.value.end)
    params.append('page', String(page.value))
    params.append('pageSize', String(pageSize.value))
    const response = await fetch('http://localhost:3000/api/userlogs?' + params.toString())
    const data = await response.json()
    if (data.success && data.data) {
      logs.value = data.data.map(log => ({ ...log }))
      total.value = data.total || 0
    } else {
      error.value = data.message || '加载失败'
    }
  } catch (err) {
    error.value = '加载失败'
  } finally {
    loading.value = false
  }
}

function onQuery() {
  page.value = 1
  loadLogs()
}

function onPageChange(newPage: number) {
  page.value = newPage
  loadLogs()
}

function goHome() {
  router.push('/home')
}

function goStats() {
  router.push('/stats')
}

async function handleAdd() {
  try {
    const res = await fetch('http://localhost:3000/api/userlogs', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newLog.value)
    })
    const data = await res.json()
    if (data.success) {
      showAdd.value = false
      Object.keys(newLog.value).forEach(k => newLog.value[k] = '')
      await loadLogs()
      alert('添加成功！')
    } else {
      alert(data.message || '添加失败')
    }
  } catch (err) {
    alert('添加失败')
  }
}

async function handleDelete(no: number) {
  if (!confirm('确定要删除这条日志吗？')) return
  try {
    const res = await fetch(`http://localhost:3000/api/userlogs/${no}`, { method: 'DELETE' })
    const data = await res.json()
    if (data.success) {
      await loadLogs()
      alert('删除成功！')
    } else {
      alert(data.message || '删除失败')
    }
  } catch (err) {
    alert('删除失败')
  }
}

function startEdit(log) {
  log.editing = true;
  log.editCache = { ...log };
}
async function saveEdit(log) {
  try {
    const res = await fetch(`http://localhost:3000/api/userlogs/${log.no}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(log.editCache)
    })
    const data = await res.json()
    if (data.success) {
      Object.assign(log, log.editCache)
      log.editing = false
      alert('更新成功！')
    } else {
      alert(data.message || '更新失败')
    }
  } catch (err) {
    alert('更新失败')
  }
}
function cancelEdit(log) {
  log.editing = false;
}

onMounted(() => {
  loadLogs()
  loadTools()
})
</script>

<style scoped>
.user-log-view {
  padding: 20px;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
}
h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
}
h2 {
  color: #34495e;
  margin-bottom: 20px;
}
.logs-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
.loading, .error, .empty {
  padding: 20px;
  text-align: center;
  color: #6c757d;
}
.error {
  color: #dc3545;
}
.logs-table {
  overflow-x: auto;
}
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
}
th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}
tr:hover {
  background-color: #f8f9fa;
}
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}
.btn-primary {
  background-color: #007bff;
  color: white;
}
.btn-primary:hover {
  background-color: #0056b3;
}
.btn-secondary {
  background-color: #6c757d;
  color: white;
  margin-right: 5px;
}
.btn-secondary:hover {
  background-color: #545b62;
}
.btn-danger {
  background-color: #dc3545;
  color: white;
}
.btn-danger:hover {
  background-color: #c82333;
}
.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}
.pagination { display: flex; justify-content: center; align-items: center; gap: 10px; margin: 20px 0; }
.pagination button { padding: 6px 16px; border: none; border-radius: 4px; background: #007bff; color: #fff; cursor: pointer; font-size: 14px; }
.pagination button:disabled { background: #ccc; cursor: not-allowed; }
.modal { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center; }
.modal-content { background: #fff; padding: 30px; border-radius: 8px; min-width: 300px; display: flex; flex-direction: column; gap: 10px; }
.query-row { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; }
.wide-form { display: flex; flex: 1; gap: 10px; max-width: 900px; min-width: 600px; }
.add-btn { min-width: 80px; font-size: 16px; margin-left: 0; }
.query-input, .btn { height: 40px; }
.btn-wide { min-width: 120px; width: 120px; }
.modal-content select { height: 40px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; padding: 0 8px; }
.modal-content input, .modal-content select, .modal-content button {
  font-size: 16px;
  font-family: inherit;
  text-align: center;
  color: #222;
}
.modal-content input::placeholder, .modal-content select, .modal-content button {
  color: #222;
  opacity: 1;
}
.modal-content h3 { text-align: center; }
.top-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}
.stats-btn {
  height: 44px;
  min-width: 120px;
  font-size: 16px;
  margin-left: 24px;
}
@media (max-width: 768px) {
  .logs-table {
    font-size: 14px;
  }
  th, td {
    padding: 8px;
  }
}
</style> 